package com.briup.jd2511.jd2511bookstore.controller;

import com.briup.jd2511.jd2511bookstore.response.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cookie")
public class CookieController {
    @PostMapping("/login")
    public Result<String> login(HttpServletRequest request,
                                HttpServletResponse response) {
        // 获取请求中的参数值
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 验证登录信息
        if ("admin".equals(username) && "admin".equals(password)) {
            // 设置cookie
            response.addCookie(new Cookie("username", username));
            return Result.success("登陆成功");
        }else {
            return Result.error("用户名或密码错误");
        }
    }

    @GetMapping("/user")
    public Result<String> getUser(HttpServletRequest request) {
        // 从请求中获取cookie携带的信息
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            // 输出cookie中的内容
            System.out.println(cookie.getName() + ":" + cookie.getValue());
        }
        return Result.success("获取用户信息成功");
    }
}
